function initMasher() {
  var user = $('#userid').val();
  var server = $('#server').val();
  wave.getState().submitDelta({'user': user, 'server': server, 'state': 'select'});
}

function create_url(picid) {
    var user = wave.getState().get('user');
    var server = wave.getState().get('server');
    var head = server + '/' + user + '/pictures';
    var mid = ((picid.length > 0) ? ("/" + picid) : "");
    var tail = '?callback=?&auth=' + user;
    return head+mid+tail;
}


function renderSelector() {
  $('#nav').css('display', 'block');
  $('#setup').css('display', 'none');
  $('#picture_list').empty();
  $('#pictures').css('display', 'block');

  var count = wave.getState().get('count', '20');
  var start = wave.getState().get('start', '0');
  var pagination = '&count=' + count + '&start=' + start;
  $.getJSON(create_url("") + pagination, function (data) {
    for(var i in data.result) {
      pic = data.result[i];
      picurl = create_url(pic.id) + '&size=thumb';
      $('#picture_list').append('<div class="grid_element_wrapper" id="' + pic.id + '">' +
      '<div class="grid_element"><a href="#" onClick="setPicture(\'' + pic.id + '\')">' +
      '<img id="thumb" class="grid_img" src="' + picurl + '"/></a></div></div>');
    }
    gadgets.window.adjustHeight();
  });
}

function setPicture(pic_id) {
    delta = {'state': 'display', 'pic': pic_id};
    wave.getState().submitDelta(delta);
}

function renderPicture() {
    picid = wave.getState().get('pic');
    $('#setup').css('display', 'none');
    $('#picture_list').empty();
    $('#pictures').css('display', 'none');    
    $('#current_picture').css('display', 'block');
    var curr = $("#current_picture");
    curr.css('display', 'block');
    // new image object
    var img = new Image();
    // image onload
    $(img).load(function () {
        $(curr).removeClass('loading').append(this);
        gadgets.window.adjustHeight();
    }).attr('src', create_url(picid) + '&size=vga');
}

function next() {
  var start = parseInt(wave.getState().get('start', '0'));
  start += 20;
  wave.getState().submitDelta({'start': ''+start});
}

function prev() {
  var start = parseInt(wave.getState().get('start', '0'));
  start -= 20;
  wave.getState().submitDelta({'start': ''+start});
}

function stateUpdated() {
  // msg.createDismissibleMessage("state: " + wave.getState().get('state'));
  // gadgets.window.adjustHeight();
  switch (wave.getState().get('state')) {
    case 'init':
      break;
    case 'select':
      renderSelector();
      break;
    case 'display':
      renderPicture();
      break;
    default:
      wave.getState().submitDelta({'state': 'init'});
  }
}

function init() {
  if (wave && wave.isInWaveContainer()) {
    gadgets.window.adjustHeight();
    wave.setStateCallback(stateUpdated);
  }
}
